package pl.edu.utp.kursy;

import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import pl.edu.utp.kursy.database.DatabaseManager;
import pl.edu.utp.kursy.database.Inovice;
import pl.edu.utp.kursy.database.InoviceRow;
import pl.edu.utp.kursy.pdf.InoviceFields;
import pl.edu.utp.kursy.utils.FileUtil;

public class InovicesPanel extends javax.swing.JPanel {
    
    {
        UIManager.put("OptionPane.noButtonText", "Nie");
        UIManager.put("OptionPane.yesButtonText", "Tak");
        UIManager.put("OptionPane.cancelButtonText", "Anuluj");
    }
    
    
    private DatabaseManager dataManager;
    
    public InovicesPanel(DatabaseManager dataManager) {
        initComponents();
        
        this.dataManager = dataManager;
        initInovicesTable();
        refresh();
    }

    private void initInovicesTable(){
        inovicesTable.setRowHeight(25);
    }
    
    public final void refresh(){
        ArrayList<Inovice> inovices = dataManager.getAllInovices();
        inovicesTable.setModel(new InovicesTableModel(inovices));
        inovicesTable.repaint();
        
        new ButtonColumn(inovicesTable, createOpenInoviceAction(), 8);
        new ButtonColumn(inovicesTable, createRemoveInoviceAction(), 9);
        
        inovicesTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        inovicesTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        inovicesTable.getColumnModel().getColumn(0).setCellRenderer(new HeaderRenderer());
    }
    
    private Action createOpenInoviceAction(){
        return new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
                openSelectedInovice();
            }
        };
    }
    
    private Action createRemoveInoviceAction(){
        return new AbstractAction(){
            @Override
            public void actionPerformed(ActionEvent e) {
                removeSelectedInovice();
            }
        };
    }
    
    private Inovice getSelectedInovice(){
        int selectedRow = inovicesTable.getSelectedRow();
        InovicesTableModel model = (InovicesTableModel)inovicesTable.getModel();
        return model.getInoviceAt(selectedRow);
    }
    
    private void openSelectedInovice(){
        FileUtil.openFile(getSelectedInovice().getInoviceFilePath());
    }
    
    private void removeSelectedInovice(){
        Inovice inovice = getSelectedInovice();
        int option = JOptionPane.showConfirmDialog(null,
                                                    getString("inovice_remove_confirmation_message"),
                                                    getString("inovice_remove_confirmation_title"),
                                                    JOptionPane.YES_NO_OPTION,
                                                    JOptionPane.WARNING_MESSAGE);
        if(option == JOptionPane.YES_OPTION){
            dataManager.deleteInovice(inovice);
            FileUtil.deleteFile(inovice.getInoviceFilePath());
            refresh();
        }
    }
    
    protected String getString(String key){
        return StringsProperties.getString(key);
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        inovicesScrollPanel = new javax.swing.JScrollPane();
        inovicesTable = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        inovicesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        inovicesTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        inovicesScrollPanel.setViewportView(inovicesTable);

        add(inovicesScrollPanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane inovicesScrollPanel;
    private javax.swing.JTable inovicesTable;
    // End of variables declaration//GEN-END:variables
    
    private class InovicesTableModel extends AbstractTableModel{
        
        private ArrayList<Inovice> inovices;
        
        private String[] columns = new String[]{
            getString("inovice_lp"),
            getString("inovice_seller"),
            getString("inovice_customer"),
            getString("inovice_issued_date"),
            getString("inovice_positions"),
            getString("inovice_netto_price"),
            getString("inovice_vat_price"),
            getString("inovice_brutto_price"),
            "",
            ""
        };
        
        public InovicesTableModel(ArrayList<Inovice> inovices){
            this.inovices = inovices;
        }

        @Override
        public int getRowCount() {
            return inovices.size();
        }

        @Override
        public int getColumnCount() {
            return columns.length;
        }

        @Override
        public String getColumnName(int column) {
            return columns[column];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if(columnIndex == 8 || columnIndex == 9){
                return true;
            }
            return false;
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch(columnIndex){
                case 0:
                    
                    return inovices.get(rowIndex).getId();
                    
                case 1:
                    
                    return inovices.get(rowIndex).getSellerName();
                    
                case 2:
                    
                    return inovices.get(rowIndex).getCustomerName();
                    
                case 3:
                    
                    return new SimpleDateFormat(InoviceFields.DATETIME_FORMAT).format(inovices.get(rowIndex).getIssueDate()).toString();
                    
                case 4:
                    
                    String positions = "";
                    boolean firstPosition = true;
                    for(InoviceRow row: inovices.get(rowIndex).getInoviceRows()){
                        if(firstPosition){
                            positions = row.getName();
                            firstPosition = false;
                        }else{
                            positions = String.format("%s, %s", positions, row.getName());
                        }
                    }
                    
                    return positions;
                    
                case 5:
                    
                    return String.format("%.2f", inovices.get(rowIndex).getValueNetto());
                    
                case 6:
                    
                    return String.format("%.2f", inovices.get(rowIndex).getValueVat());
                    
                case 7:
                    return String.format("%.2f", inovices.get(rowIndex).getValueBrutto());
                case 8:
                    return getString("inovice_open");
                case 9:
                    return getString("inovice_remove");
                    
            }
            return "";
        }
        
        public Inovice getInoviceAt(int position){
            return inovices.get(position);
        }
    }
    
    private class HeaderRenderer extends DefaultTableCellRenderer{

        public HeaderRenderer(){
            super();
            setBackground(UIManager.getColor("TableHeader.background"));
        }
    }
}